<template>
  <div id="app">
    <div class="layout">
      <Layout>
        <Header>
          <TopBar
              :top-menu="topMenu"/>
        </Header>

        <Layout>
          <Sider :style="{background: '#fff'}">
            <LeftNav :left-active="leftActive" :left-menu="leftMenu" :left-open-name="leftOpenName"
                     :menu-current="menuCurrent" :order-number="orderNumber" :show-sub-openmenu="showSubOpenmenu"
                     :show-submenu="showSubmenu"/>
          </Sider>

          <Layout :style="{padding: '10px 10px 170px 10px'}">
            <Content>
              <router-view/>
            </Content>
          </Layout>
        </Layout>
      </Layout>
    </div>
    <div style="height: 0; overflow: hidden">
      <ElementPrint :data="printData" ref="print"/>
    </div>
  </div>
</template>
<script>
import 'element-ui/lib/theme-chalk/index.css';
import './assets/css/public.css';
import './assets/css/elecustom.css';
import './assets/css/page.css';
import './assets/css/iconfont.css';
import {getEdition} from '@/api/setup';
import {selectStore, waitReceiv} from '@/api/public';
import index from './api/index';
import {mapActions, mapGetters, mapMutations, mapState} from 'vuex';
import {orderContent} from "@/api/order";
import ElementPrint from "@/views/order/components/elementPrint";
import TopBar from "@/components/main/TopBar.vue";
import LeftNav from "@/components/main/LeftNav.vue";
import {appendedLeftMenuData} from "@/components/main/AppendLeftMenu";

export default {
  name: 'App',
  components: {
    LeftNav,
    TopBar,
    ElementPrint
  },
  data() {
    return {
      isCollapsed: false,
      printData: {},
      orderNumber: '',
      shopYysj: '',
      copy: '',
      menuCurrent: '/',
      leftActive: '1',
      leftOpenName: ['1'],
      topMenu: [],
      leftMenu: [],
      leftDataLength: [],
      newsUrl: require('@/assets/audio/newsUrl.mp3'),
      urgeOrderUrl: require('@/assets/audio/urgeOrderUrl.mp3'),
      cancelOrderUrl: require('@/assets/audio/cancelOrderUrl.mp3'),
      retreatOrderUrl: require('@/assets/audio/retreatOrderUrl.mp3'),
      autoOrderUrl: require('@/assets/audio/autoOrderUrl.mp3'),
      edition: '',//判断微擎版本和独立版2是独立版
      // role:'', //判断微擎版本和的超级权限，==founder的时候是超级管理员才显示左边菜单的超级权限
      systemData: {},
    };
  },
  async created() {
    await this.getVersionInfo();
    await this.fetchSystemConfig();
    await this.loadMenu();
    this.getTitle();
    this.getWaitReceiv();
    this.getMarket();
    this.edition = sessionStorage.getItem('edition') ? sessionStorage.getItem('edition') : '';
    if (this.edition == '') {
      this.getEdition();
    }

    this.menuCurrent = this.storeMenuCurrent;
    this.menuCurrent = sessionStorage.getItem('menuCurrent') ? sessionStorage.getItem('menuCurrent') : '/';
    this.leftActive = sessionStorage.getItem('leftActive') ? sessionStorage.getItem('leftActive') : '1-1';
    this.leftOpenName = sessionStorage.getItem('leftOpenName') ? JSON.parse(sessionStorage.getItem('leftOpenName')) : ['1'];
  },
  computed: {

    ...mapState(['updataOrder', 'storeMenuCurrent', {nav: 'menu'}, 'menu'])
  },
  watch: {
    updataOrder() {
      this.getWaitReceiv();
    }
  },
  methods: {
    ...mapActions(['getStoreOrderList']),
    ...mapActions([
      'getVersionInfo', 'fetchSystemConfig', 'fetchMenu'
    ]),
    ...mapMutations(['searchMarket', 'setmenuCurrent',]),
    ...mapGetters([
      'getSystemInfo',
      'getMenu',
    ]),
    // start查询商家
    async getMarket() {
      const {data} = await selectStore();
      this.searchMarket(data);
    },
    // end查询商家
    // start订单处理
    async getWaitReceiv() {
      const {data} = await waitReceiv();
      this.orderNumber = data;
    },
    updataNumber(status) {
      if (status) this.getWaitReceiv();
    },
    // end订单处理
    async getTitle() {
      const data = this.getSystemInfo();
      document.title = data.name ? data.name + '-管理后台' : '管理后台';
      this.systemData = data
      this.upLoad2(this);
    },

    async getEdition() {
      const {data} = await getEdition();
      this.edition = data;
      sessionStorage.setItem('edition', data);
    },

    async loadMenu() {
      if (isMenuCached()) {
        this.topMenu = JSON.parse(sessionStorage.getItem('topMenu'));
        this.leftMenu = JSON.parse(sessionStorage.getItem('leftMenu'));
        return;
      }
      await this.fetchMenu();
      this.topMenu = this.getMenu() ? this.getMenu() : [];
      this.leftMenu = this.getMenu() ? this.getMenu() : [];
      // todo : 有待厘清这个push的目的
      this.leftMenu.push(
          ...appendedLeftMenuData);

      sessionStorage.setItem('topMenu', JSON.stringify(this.topMenu)); //设置菜单缓存
      sessionStorage.setItem('leftMenu', JSON.stringify(this.leftMenu)); //设置菜单缓存

      function isMenuCached() {
        let topMenuItems = sessionStorage.getItem('topMenu');
        return topMenuItems && (topMenuItems.length > 0);
      }
    },


    upLoad() {
      const publishUrl = 'wss://' + 'bkycms.com' + ':9875';
      const backendPath = index.isDev ? publishUrl : 'wss://' + window.location.host + ':9875';
      if ('WebSocket' in window) {
        // alert("您的浏览器支持 WebSocket!");
        // 打开一个 web socket
        var that = this;
        // console.log('publishUrl',backendPath)
        var ws = new WebSocket(backendPath);
        console.log(ws);
        ws.onopen = function () {
          ws.send('发送数据');
          console.log('连接成功');
          setInterval(function () {
            ws.send('beatheart');
          }, 3000);
        };
        ws.onmessage = function (evt) {
          // var received_msg = evt.data;
          console.log('接收到消息' + evt.data);
          let hdData = JSON.parse(evt.data);
          if (hdData.num && hdData.voiceName) {
            that.Orderprocessing1(hdData.num);
            var params = {
              page: '1',
              state: '1'
            };
            that.getStoreOrderList(params);
          }
          // ws.send('等待接收数据')
        };
        ws.onclose = function () {
          console.log('连接已关闭');
          // alert("连接已关闭...");
        };
      } else {
        // 浏览器不支持 WebSocket
        alert('您的浏览器不支持 WebSocket!');
      }
    },
    upLoad2(_that) {
      _that.lockReconnect = false; //避免ws重复连接
      _that.ws = null; // 判断当前浏览器是否支持WebSocket
      const publishUrl = 'wss://' + 'bkycms.com' + ':9875';
      var wsUrl = index.isDev ? publishUrl : 'wss://' + window.location.host + ':9875';
      createWebSocket(wsUrl); //连接ws
      function createWebSocket(url) {
        try {
          if ('WebSocket' in window) {
            _that.ws = new WebSocket(url);
          }
          initEventHandle();
        } catch (e) {
          reconnect(url);
          // console.log(e);
        }
      }

      function initEventHandle() {
        _that.ws.onclose = function () {
          reconnect(wsUrl);
          // console.log("llws连接关闭!"+new Date().toLocaleString());
        };
        _that.ws.onerror = function () {
          reconnect(wsUrl);
          // console.log("llws连接错误!");
        };
        _that.ws.onopen = function () {
          heartCheck.reset().start(); //心跳检测重置
          // console.log("llws连接成功!"+new Date().toLocaleString());
        };
        _that.ws.onmessage = function (event) {
          //如果获取到消息，心跳检测重置
          heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
          console.log('llws收到消息啦:' + event.data);
          if (event.data) {
            //处理业务逻辑
            var hdData = JSON.parse(event.data);
            if (hdData.voiceName) {
              if (hdData.uniacid == _that.systemData.uniacid && hdData.storeId == _that.systemData.storeId) {
                // let hdData = event.data
                if (hdData.num && hdData.voiceName) {
                  _that.Orderprocessing1(hdData.num, hdData.voiceName);
                  var params = {
                    page: '1',
                    state: '1',
                  };
                  _that.getStoreOrderList(params);
                }
                if (hdData.orderId) {
                  console.log('orderId', hdData)
                  print(hdData.orderId);
                }
              }
            }
          }
        };
      }

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = function () {
        _that.ws.close();
      };

      async function print(id) {
        const {data} = await orderContent({orderId: id});
        console.log(data)
        Object.keys(data).map(key => {
          _that.printData = data[key];
          _that.$nextTick(() => {
            _that.$refs.print.printElement(key);
          });
        })
      }

      function reconnect(url) {
        if (_that.lockReconnect) return;
        _that.lockReconnect = true;
        setTimeout(function () {
          //没连接上会一直重连，设置延迟避免请求过多
          createWebSocket(url);
          _that.lockReconnect = false;
        }, 2000);
      }

      //心跳检测
      var heartCheck = {
        timeout: 1000, //1分钟发一次心跳
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
          clearTimeout(this.timeoutObj);
          clearTimeout(this.serverTimeoutObj);
          return this;
        },
        start: function () {
          var self = this;
          this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            _that.ws.send('ping');
            // console.log("ping!")
            self.serverTimeoutObj = setTimeout(function () {
              //如果超过一定时间还没重置，说明后端主动断开了
              _that.ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout);
          }, this.timeout);
        }
      };
    },
    Orderprocessing1(num, name) {
      var vid = ''
      switch (name) {
        case 'newOrder':
          vid = document.getElementById('newsUrl')
          break;
        case 'reminderOrder':
          vid = document.getElementById('urgeOrderUrl')
          break;
        case 'cancelOrder':
          vid = document.getElementById('cancelOrderUrl')
          break;
        case 'chargebackOrder':
          vid = document.getElementById('retreatOrderUrl')
          break;
        case 'receiving':
          vid = document.getElementById('autoOrderUrl')
          break;
      }
      var start = 0; //定义循环的变量
      var times = num; //定于循环的次数
      vid.addEventListener('ended', function () {
        vid.play(); //启动音频，也就是播放
        start++; //循环
        start == times && vid.pause(); //也就是当循环的变量等于次数的时候，就会终止循环并且关掉音频
      });
      vid.play(); //启动音频，用于第一次启动
    },
    showToggle(name) {
      this.$router.push({path: name});
      this.setmenuCurrent(name);
      sessionStorage.clear('leftActive');
      this.leftActive = '1';
      this.leftOpenName = ['1'];
      sessionStorage.setItem('menuCurrent', name);
    },
    showSubOpenmenu(name) {
      // console.log('open',name)
      sessionStorage.setItem('leftOpenName', JSON.stringify(name));
      this.leftOpenName = name;
    },
    showSubmenu(name) {
      // console.log(name)
      sessionStorage.setItem('leftActive', name);
      this.leftActive = name;
    },


  },
  destroyed() {
    console.log('页面销毁')
    //禁止重连
    this.lockReconnect = true
    this.ws.close()
  },
};
</script>
<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #333;
  height: 100%;
}

.layout {
  height: 100%;
  min-width: 1700px !important;
}

.ivu-layout-sider-children {

}

.ivu-menu-vertical.ivu-menu-light:after {
  width: 0px !important;
}


.ivu-layout {
  height: 100%;
}

.ivu-layout-header {
  background: linear-gradient(90deg, #1d42ab, #2173dc, #1e93ff) !important;
  padding: 0 !important;
}

.ivu-menu-primary {
  background: none !important;
}

.i-layout-header-logo img {
  height: 80%;
  vertical-align: middle;
}

.ivu-menu-light {
  text-align: left;
  height: 100%;
}

.ivu-menu-horizontal {
  height: 62px !important;
  line-height: 62px !important;
}

.oneMenu .ivu-menu-item {
  border-bottom: 2px solid transparent;
}

.oneMenu .ivu-menu-item-active {
  border-bottom: 2px solid #fff;
}


.yysj {
  top: 45px !important;
  left: 1570px !important;
}

.copayRight {
  padding: 10px;
  width: 100%;
  background: #fff;
  position: fixed;
  bottom: 0;
  line-height: 24px;
}

.el-dropdown-menu {
  width: 100px;
}
</style>
